////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//                                                                                                                            //
//                                                         WNProject                                                          //
//                                                                                                                            //
//            This file is distributed under the BSD 2-Clause open source license. See License.txt for details.               //
//                                                                                                                            //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#pragma once

#ifndef __WN_CONCURRENCY_RECURSIVE_MUTEX_INL__
#define __WN_CONCURRENCY_RECURSIVE_MUTEX_INL__

#include "WNCore/inc/WNAssert.h"

#ifdef _WN_WINDOWS
    #include <windows.h>
#elif defined _WN_LINUX
    #include <pthread.h>
#endif

namespace WNConcurrency {
    WN_FORCE_INLINE WNRecursiveMutex::WNRecursiveMutex() {
        #ifdef _WN_WINDOWS
            InitializeCriticalSection(&mCriticalSection);
        #elif defined _WN_LINUX
            pthread_mutexattr_t attributes;

            WN_RELEASE_ASSERT(pthread_mutexattr_init(&attributes) == 0);
            WN_RELEASE_ASSERT(pthread_mutexattr_settype(&attributes, PTHREAD_MUTEX_RECURSIVE) == 0);
            WN_RELEASE_ASSERT(pthread_mutex_init(&mMutex, &attributes) == 0);
            WN_RELEASE_ASSERT(pthread_mutexattr_destroy(&attributes) == 0);
        #endif
    }

    WN_FORCE_INLINE WNRecursiveMutex::~WNRecursiveMutex() {
        #ifdef _WN_WINDOWS
            DeleteCriticalSection(&mCriticalSection);
        #elif defined _WN_LINUX
            WN_RELEASE_ASSERT(pthread_mutex_destroy(&mMutex) == 0);
        #endif
    }

    WN_FORCE_INLINE WN_VOID WNRecursiveMutex::Lock() {
        #ifdef _WN_WINDOWS
            EnterCriticalSection(&mCriticalSection);
        #elif defined _WN_LINUX
            WN_RELEASE_ASSERT(pthread_mutex_lock(&mMutex) == 0);
        #endif
    }

    WN_FORCE_INLINE WN_BOOL WNRecursiveMutex::TryLock() {
        #ifdef _WN_WINDOWS
            return(TryEnterCriticalSection(&mCriticalSection) != 0 ? WN_TRUE : WN_FALSE);
        #elif defined _WN_LINUX
            return(pthread_mutex_trylock(&mMutex) == 0 ? WN_TRUE : WN_FALSE);
        #endif
    }

    WN_FORCE_INLINE WN_VOID WNRecursiveMutex::Unlock() {
        #ifdef _WN_WINDOWS
            LeaveCriticalSection(&mCriticalSection);
        #elif defined _WN_LINUX
            WN_RELEASE_ASSERT(pthread_mutex_unlock(&mMutex) == 0);
        #endif
    }
}

#endif // __WN_CONCURRENCY_RECURSIVE_MUTEX_INL__
